﻿using MudBlazor;
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using Tool.Models;
using Volo.Abp.DependencyInjection;

namespace Tool.Services
{
    public class LoginService : IScopedDependency
    {
        private readonly IHttpClientFactory httpClientFactory;

        public LoginService(IHttpClientFactory httpClientFactory)
        {
            this.httpClientFactory = httpClientFactory;
        }

        public async Task<HttpResponseHeaders> Login(string selectedSite)
        {
            string loginUrl = $"/login/";
            string authenticateUrl = $"/authenticate/";
            string logoutUrl = "/logout/";
            HttpResponseHeaders responseHeaders;
            try
            {
                // 创建 HttpClient 并发送请求
                using (var httpClient = httpClientFactory.CreateClient(selectedSite))
                {
                    httpClient.DefaultRequestVersion = new Version(2, 0);
                    httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;

                    await httpClient.GetAsync(logoutUrl);

                    var authRequest = new HttpRequestMessage(HttpMethod.Post, authenticateUrl);
                    authRequest.Headers.Add("Referer", $"{httpClient.BaseAddress}{loginUrl.TrimStart('/')}");
                    authRequest.Headers.Add("Accept", "application/json; charset=UTF-8");
                    authRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0");

                    // 发送 GET 请求
                    var response = await httpClient.GetAsync(loginUrl);

                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Response Status: Success");

                        // 获取响应头中的 Set-Cookie 字段
                        if (response.Headers.TryGetValues("Set-Cookie", out var cookieValues))
                        {
                            foreach (var cookie in cookieValues)
                            {
                                Console.WriteLine("Received Set-Cookie: " + cookie);
                                authRequest.Headers.Add("Cookie", cookie);
                            }
                        }

                        // 3. 获取 csrftoken（从 Cookie 中）
                        // HttpClient 没有 GetCookies 方法，需手动解析 Set-Cookie
                        var csrfCookie = cookieValues?.FirstOrDefault(c => c.Contains("csrftoken="));
                        if (csrfCookie != null)
                        {
                            var csrfValue = csrfCookie.Split(';').FirstOrDefault(x => x.Trim().StartsWith("csrftoken="));
                            if (csrfValue != null)
                            {
                                var token = csrfValue.Substring("csrftoken=".Length);
                                authRequest.Headers.Add("X-CSRFToken", token);
                            }
                        }

                        // 构建 Form 数据
                        var collection = new List<KeyValuePair<string, string>>();
                        collection.Add(new("username", "likeshan"));
                        collection.Add(new("password", "Sfqd@20220428"));
                        var content = new FormUrlEncodedContent(collection);
                        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                        authRequest.Content = content;
                        // 显式设置 Content-Type


                        var postResponse = await httpClient.SendAsync(authRequest);
                        Console.WriteLine(postResponse.Version);
                        // 6. 处理响应
                        if (postResponse.IsSuccessStatusCode)
                        {
                            responseHeaders = postResponse.Headers;
                            var responseBody = await postResponse.Content.ReadFromJsonAsync<ResponseDto<string>>();
                            if (responseBody == null || responseBody.Status != 0)
                            {
                                return default;
                            }
                            else
                            {
                                return responseHeaders;
                            }
                        }
                        else
                        {
                            Console.WriteLine($"请求失败，状态码: {postResponse.StatusCode}");
                            Console.WriteLine($"原因: {postResponse.ReasonPhrase}");
                        }
                    }
                    else
                    {
                        if (response.StatusCode == HttpStatusCode.Found)
                        {
                            responseHeaders = response.Headers;
                            return responseHeaders;
                        }

                    }
                }
            }
            catch (HttpRequestException httpEx)
            {
                // 专门捕获 HTTP 层异常，可能包含内部异常
                Console.WriteLine($"HTTP 请求异常: {httpEx.Message}");
                if (httpEx.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {httpEx.InnerException.Message}");
                    // 这里可能会看到 "The credentials supplied to the package were not recognized"
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
                if (ex is CryptographicException cryptoEx)
                {
                    Console.WriteLine($"加密错误详情: {cryptoEx.Message}");
                }
            }

            return default;
        }

    }
}

